﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace ConcordWinManager
{
    public partial class ConsultantEditForm : Form
    {
        public Consultant consultant;       

        private string mode;

        private Form parentForm;

        public ConsultantEditForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Конструктор на добавление
        /// </summary>
        /// <param name="parentForm"></param>
        /// <param name="mode"></param>
        public ConsultantEditForm(Form parentForm, string mode)
        {
            InitializeComponent();
            this.mode = mode;

            this.Text = string.Format("Консультант [{0}]", mode);

            this.parentForm = parentForm;

            if (this.mode == "Добавление")
            {
                consultant = new Consultant();                
                this.act = true;
            }            
        }

        /// <summary>
        /// Конструктор на изменение
        /// </summary>
        /// <param name="parentForm"></param>
        /// <param name="mode"></param>
        /// <param name="id"></param>
        public ConsultantEditForm(Form parentForm, string mode, int id)
        {
            InitializeComponent();

            this.parentForm = parentForm;

            this.Text = string.Format("Консультант [{0}]", mode);

            this.mode = mode;

            if (mode == "Изменение")
            {
                consultant = new Consultant();
                Tools.RunWithProgressIndicator(this, delegate
                {
                    consultant.SelectById(id);

                    if (consultant.id_address != 0)
                    {
                        consultant.address = new Address(consultant.id_address);
                        tbxAddressText.Text = consultant.address.RebuildAddressText();
                    }

                    consultant.rezident = new Rezident().SelectById(consultant.id_rezident);

                    tbxRezidentName.Text = consultant.rezident.Name;
                });

                tbxFamily.Text = consultant.Family;
                tbxName.Text = consultant.Name;
                tbxFName.Text = consultant.FName;

                tbxFamily2.Text = consultant.Family2;
                tbxName2.Text = consultant.Name2;
                tbxFName2.Text = consultant.FName2;

                tbxRezidentName.Text = consultant.rezident.Name;

               

                if (consultant.user.id_user != 0)
                {
                    tbxUsername.Text = consultant.user.Username;
                    cbxIsAdminRole.Checked = consultant.user.IsAdminRole;
                    cbxIsAccountLocked.Checked = consultant.user.IsAccountLocked;
                    cbxCanAddContact.Checked = consultant.user.CanAddContract;
                    cbxCanDeleteContract.Checked = consultant.user.CanDeleteContract;
                    cbxCanDeleteContragent.Checked = consultant.user.CanDeleteContragent;
                }

                if (consultant.doverennost.id_doverennost != 0)
                {
                    tbxDoverennostText.Text = consultant.doverennost.ReturnDoverennostText();
                }
            }

            this.act = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnRezidentChange_Click(object sender, EventArgs e)
        {
            RezidentForm rezidentForm = new RezidentForm(this);
            rezidentForm.ShowDialog();

            consultant.rezident = rezidentForm.rezident;
            tbxRezidentName.Text = rezidentForm.rezident.Name;
        }

        private void btnAddressChange_Click(object sender, EventArgs e)
        {
            AddressEditForm addressEditForm;

            if (consultant.address.id_address != 0)
            {
                addressEditForm = new AddressEditForm(this, "Изменение", consultant.address.id_address);
            }
            else
            {
                addressEditForm = new AddressEditForm(this, "Добавление");
            }

            addressEditForm.ShowDialog();            

            tbxAddressText.Text = addressEditForm.address.RebuildAddressText();
            consultant.address = addressEditForm.address;
        }

        private bool act = false;

        private void rebuildConsultantData(object sender, EventArgs e)
        {
            if (act)
            {
                this.consultant.Family = tbxFamily.Text.Trim();
                this.consultant.Name = tbxName.Text.Trim();
                this.consultant.FName = tbxFName.Text.Trim();
            }
        }

        private bool IsFormValid()
        {
            if (tbxFamily.Text.Length == 0 ||
                tbxName.Text.Length == 0 ||
                tbxFName.Text.Length == 0 ||
                tbxFamily2.Text.Length == 0 ||
                tbxName2.Text.Length == 0 ||
                tbxFName2.Text.Length == 0 ||
                tbxAddressText.Text.Length == 0)
            {
                MessageBox.Show("Не все обязательные для заполнения поля заполнены", "Внимание!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            bool bSuccessfully = false;

            try
            {
                if (IsFormValid())
                {
                    this.consultant.Name = tbxName.Text.Trim();
                    this.consultant.Name2 = tbxName2.Text.Trim();
                    this.consultant.Family = tbxFamily.Text.Trim();
                    this.consultant.Family2 = tbxFamily2.Text.Trim();
                    this.consultant.FName = tbxFName.Text.Trim();
                    this.consultant.FName2 = tbxFName2.Text.Trim();
                    
                    if (this.mode == "Изменение")
                    {
                        Tools.RunWithProgressIndicator(this, delegate { consultant.Update(); });

                        MessageBox.Show("Консультант изменен успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        if (mode == "Добавление")
                        {
                            Tools.RunWithProgressIndicator(this, delegate { consultant.Insert(); });

                            MessageBox.Show("Консультант добавлен успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }

                    //if (parentForm is ConsultantForm)
                    //{
                    //    (parentForm as ConsultantForm).UpdateForm();
                    //}

                    bSuccessfully = true;
                }
            }
            catch
            {
                ;
            }

            if (bSuccessfully)
            {
                this.Close();
            }
        }


        private bool IsUserInfoValid()
        {
            //User user = new User();
            if (consultant.id_consultant == 0)
            {
                MessageBox.Show("Сначала добавьте консультанта", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (tbxUsername.Text.IndexOf(" ") > -1)
            {
                MessageBox.Show("Логин не может содержать пробелов", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (tbxUsername.Text.Length < 3)
            {
                MessageBox.Show("Логин слишком короткий", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (tbxPassword.Text.Length < 3)
            {
                MessageBox.Show("Пароль слишком короткий", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (tbxPassword.Text != tbxConfirmPassword.Text)
            {
                MessageBox.Show("Пароль и подтверждение пароля не совпадают", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            else if (consultant.user.id_user == 0 && consultant.user.Exist(tbxUsername.Text))
            {
                MessageBox.Show("Пользователь с таким логином уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            //Regex r = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
            //if (!r.IsMatch(txtUserEmail.Text))
            //{
            //    MessageBox.Show(m_ResourceManager.GetString("Email_address_is_not_valid"));
            //    return false;
            //}

            return true;
        }

        private void btnApplyUserInfo_Click(object sender, EventArgs e)
        {
            if (IsUserInfoValid())
            {
                consultant.user.id_consultant = consultant.id_consultant;
                consultant.user.Username = tbxUsername.Text;
                consultant.user.Password = tbxPassword.Text;
                consultant.user.IsAdminRole = cbxIsAdminRole.Checked;

                if (consultant.user.id_user != 0)
                {
                    //Обновляем                   

                    Tools.RunWithProgressIndicator(this, delegate
                    {
                        consultant.user.UpdateInfo();
                    });
                    MessageBox.Show("Пользователь изменен успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    //Добавляем

                    Tools.RunWithProgressIndicator(this, delegate
                    {
                        consultant.user.Insert();
                    });
                    
                    MessageBox.Show("Пользователь добавлен успешно", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    //Обновляем права доступа
                    btnApplyUserRole_Click(this, e);
                }


            }
        }

        private void btnApplyUserRole_Click(object sender, EventArgs e)
        {
            if (consultant.user.id_user != 0)
            {
                consultant.user.IsAdminRole = cbxIsAdminRole.Checked;
                consultant.user.IsAccountLocked = cbxIsAccountLocked.Checked;
                consultant.user.CanAddContract = cbxCanAddContact.Checked;
                consultant.user.CanDeleteContract = cbxCanDeleteContract.Checked;
                consultant.user.CanDeleteContragent = cbxCanDeleteContragent.Checked;

                Tools.RunWithProgressIndicator(this, delegate
                {
                    consultant.user.UpdateRole();
                });
                MessageBox.Show("Права пользователя успешно изменены", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else 
            {
                MessageBox.Show("Пользователь не найден. Сначала создайте пользователя", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnDoverennostChange_Click(object sender, EventArgs e)
        {
            DoverennostEditForm doverennostEditForm;
            
            if (consultant.doverennost.id_doverennost != 0)
            {
                doverennostEditForm = new DoverennostEditForm(this, "Изменение", consultant.doverennost.id_doverennost, ref consultant);
                doverennostEditForm.consultant = consultant;                
            }
            else
            {
                doverennostEditForm = new DoverennostEditForm(this, "Добавление");
                doverennostEditForm.consultant = consultant;
            }            
            doverennostEditForm.ShowDialog();

            if (consultant.doverennost.id_doverennost != 0)
            {
                tbxDoverennostText.Text = consultant.doverennost.ReturnDoverennostText();
            }
        }

    }
}
